import 'dart:async';

import 'package:flutter_wan_android/api/api_server.dart';
import 'package:flutter_wan_android/bean/article_list_bean.dart';
import 'package:flutter_wan_android/bean/project_list_bean.dart';
import 'package:flutter_wan_android/blocs/base/bloc_provider.dart';
import 'package:rxdart/rxdart.dart';

class ArticleBloc extends BaseBloc {
  BehaviorSubject<List<ArticleItem>> _subject = BehaviorSubject();
  Stream<List<ArticleItem>> get stream => _subject.stream;
  List<ArticleItem> _allData = [];
  List<ArticleItem> get allData => _allData;
  StreamSubscription<List<ArticleItem>> _streamSubscription;







  Future getArticleList(pageIndex,{int id=0}) async {
    if (_streamSubscription == null) {
      _streamSubscription = _subject.listen((data) {});
    }else{
      if(_streamSubscription.isPaused){
        resumeStream();
      }
    }


    if(id!=0){
      return await ApiServer.getWXArticleList(pageIndex,id).then((project) {
        if(_allData.length>0 && pageIndex==1){
          _subject.sink.add(project.datas);
          return;
        }
        _allData.addAll(project.datas);
        _subject.sink.add(project.datas);
      }).catchError((error) => _subject.sink.addError(error));
    }
    return await ApiServer.getArticleList(pageIndex).then((project) {
      if(_allData.length>0 && pageIndex==1){
        _subject.sink.add(project.datas);
        return;
      }
      _allData.addAll(project.datas);
      _subject.sink.add(project.datas);
    }).catchError((error) => _subject.sink.addError(error));
  }

  @override
  void dispose() {
    _subject.close();
  }

  void pauseStream() {
    if (_streamSubscription != null) {
      _streamSubscription.pause();
    }
  }

  void resumeStream(){
    if (_streamSubscription != null) {
      _streamSubscription.resume();
    }
  }



}
